<template>
	<div class="hardware">
		<div class="row_content">
			<div class="row_one">
				电量
			</div>
			<div class="row_two">
				<input type="number" :value="oneName" @input="one"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one">
				通道1(10A)功率
			</div>
			<div class="row_two">
				<input  type="number" :value="twoName" @input="two"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one">
				通道1(10A)电压
			</div>
			<div class="row_two">
				<input  type="number" :value="threeName" @input="three"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one">
				通道1(10A)电流
			</div>
			<div class="row_two">
				<input type="digit" :value="fourName" @input="four"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one">
				通道1(16A)功率
			</div>
			<div class="row_two">
				<input  type="number" :value="fiveName" @input="five"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one">
				通道1(16A)电压
			</div>
			<div class="row_two">
				<input  type="number" :value="sixName" @input="six"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one">
				通道1(16A)电流
			</div>
			<div class="row_two">
				<input type="digit" :value="severName" @input="sever"/>
			</div>
		</div>
		<div class="row_content">
			<div class="row_one" @click="click">
				点击确定
			</div>
			<div class="row_one" @click="clickBtn">
				标定按键
			</div>
		</div>
		<div class="contentBox">
			<div class="itemBox" v-for="(item,index) in statuslist" :key="item.label">
				<div class="itemOneText">{{item.label}}</div>
				<div class="itemTwoText">{{item.value}}</div>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				isbtn:false,
				isEnd:false,
				statuslist:[
					{
						label:"实时电压",
						value:''
					},
					{
						label:"IGBT温度",
						value:''
					},
					{
						label:"COlL温度",
						value:''
					},
					{
						label:"故障代码",
						value:''
					},
					{
						label:"电池电压",
						value:''
					},
					{
						label:"实时电流测量值",
						value:''
					},
					{
						label:"10A通道功率",
						value:''
					},
					{
						label:"10A通道电压",
						value:''
					},
					{
						label:"10A通道电流",
						value:''
					},
					{
						label:"16A通道功率",
						value:''
					},
					{
						label:"16A通道电压",
						value:''
					},
					{
						label:"16A通道电流",
						value:''
					},
					{
						label:"10A通道功率",
						value:''
					},
					{
						label:"10A通道电压",
						value:''
					},
					{
						label:"10A通道电流",
						value:''
					},
					{
						label:"16A通道功率",
						value:''
					},
					{
						label:"16A通道电压",
						value:''
					},
					{
						label:"16A通道电流",
						value:''
					},
					{
						label:"车架号",
						value:''
					},
					{
						label:"版本号",
						value:''
					},
					{
						label:"",
						value:''
					},
				],
				oneName:"00",
				twoName:"0",
				threeName:"0",
				fourName:"0",
				fiveName:"0",
				sixName:"0",
				severName:"0",
				isFirst:false,
				timerInterVal: '', //用来实时发送
				deviceId: '', //蓝牙设备id
				serviceId: '', //蓝牙服务id
				notifycharacteristicId: '', //蓝牙特证值
				characteristicId: '',
			}
		},
		onLoad(option) {
			this.deviceId = option.deviceId;
			this.getServices();
		},
		onUnload(){
			let that = this;
			clearInterval(that.timerInterVal);
		},
		methods: {
			one(e){
				this.oneName = e.target.value;
			
			},
			two(e){
				this.twoName = e.target.value;
			},
			three(e){
				this.threeName = e.target.value;
			},
			four(e){
				this.fourName = e.target.value;
			},
			five(e){
				console.log(e.target.value);
				this.fiveName = e.target.value;
			},
			six(e){
				console.log(e.target.value);
				this.sixName = e.target.value;
			},
			sever(e){
				console.log(e.target.value);
				this.severName = e.target.value;
			},
			click(){
				this.isEnd = true;
				let that = this;
				clearInterval(that.timerInterVal);
				let buffer = that.searchCarState(true);
				that.send(buffer);
			},
			clickBtn(){
			    this.isbtn = true;
				this.isEnd = true;
				let that = this;
				clearInterval(that.timerInterVal);
				let buffer = that.searchCarState(false);
				that.send(buffer);
			},
			//获取服务UUid
			getServices() {
				let that = this;
				uni.getBLEDeviceServices({
					deviceId: that.deviceId,
					success(res) {
						console.log(123, res.services, '服务UUID')
					for(let i=0;i<res.services.length;i++)
					{
						 if(res.services[i].uuid == "0000FFF0-0000-1000-8000-00805F9B34FB")
						 {
							 that.serviceId = res.services[i].uuid || "";
						 }
					}
						that.getCharacteristics();
					},
					fail(err) {
						console.error("error", err)
					}
				})
			},
			//获取蓝牙特征值
			getCharacteristics() {
				let that = this;
				console.log(that.serviceId, '获取特性值/UUID');
				uni.getBLEDeviceCharacteristics({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					success(res) {
						console.log(1234, res, '特征值');
				for(let i=0;i<res.characteristics.length;i++)
				{
					 if(res.characteristics[i].uuid == "0000FFF2-0000-1000-8000-00805F9B34FB")
					 {
						 that.characteristicId = res.characteristics[i].uuid || "";
					 }
					 if(res.characteristics[i].uuid == "0000FFF1-0000-1000-8000-00805F9B34FB")
					 {
					 	 that.notifycharacteristicId = res.characteristics[i].uuid || "";		
					 }
				}
						that.notify();
					},
					fail(err) {
						console.error(err)
					}
				})
			},
			//开启蓝牙信息监听
			notify() {
				let that = this;
				uni.notifyBLECharacteristicValueChange({
					state: true,
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.notifycharacteristicId,
					success(res) {
						let buffer = that.searchCarState(false);
						that.timerInterVal = setInterval(() => {
							that.send(buffer);
						}, 500);
			
						uni.onBLECharacteristicValueChange(function(characteristic) {
							let x = new Uint8Array(characteristic.value);
							if (x.byteLength > 60) {
								that.updataName = that.arrayBufferUTF8ToStr(characteristic.value)
							} else {
								let strHex = ""
								let str = ""
								for (let i = 0; i < x.length; i++) {
									strHex = strHex + x[i].toString(16).padStart(2, "0")
									str = str + String.fromCharCode(x[i])
								};
								if (strHex == 43 && that.writeBool == true) {
									uni.showLoading({
										title: '更新硬件中'
									})
									that.writeBool = false;
									// that.forArrayBuffer(that.dataView,that.crcBuffer,0,133);
									that.writeTest(that.bufferName, 1, "name");
								} else if (strHex.toString() == "0643" || strHex.toString() == "06") {
			
									if (that.index < that.arrayBuffer.length) {
										that.bufferName = that.arrayBuffer[that.index];
										that.pos = 0;
										that.bytes = that.bufferName.byteLength;
										that.index++;
										that.writeTest(that.bufferName, 1, "file");
									} else {
										if (strHex.toString() == "06") {
											if (that.writeFinish == false) {
												that.writeFinish = true;
												let buffer = new ArrayBuffer(1);
												let dataView = new DataView(buffer);
												dataView.setUint8(0, 0x04);
												that.send(buffer);
											} else {
												that.writeFinish = false;
												uni.hideLoading();
											}
			
			
										} else {
											let buffer = new ArrayBuffer(128);
											let dataView = new DataView(buffer);
											for (let i = 0; i < 128; i++) {
												dataView.setUint8(i, 0x00);
											}
											that.crcBuffer = that.crc16modbus(buffer);
											let newBuffer = new ArrayBuffer(133);
											let newDataView = new DataView(newBuffer);
											newDataView.setUint8(0, 0x01);
											newDataView.setUint8(1, 0x00);
											newDataView.setUint8(2, 0xFF);
											for (let i = 3; i < 131; i++) {
												newDataView.setUint8(i, dataView.getUint8(i - 3));
											}
											newDataView.setUint8(131, that.crcBuffer[1]);
											newDataView.setUint8(132, that.crcBuffer[0]);
											that.bufferName = newBuffer;
											that.pos = 0;
											that.bytes = that.bufferName.byteLength;
											that.writeTest(that.bufferName, 0, "");
										}
			
									}
								} else if (strHex.toString() == "15") {
									let buffer = new ArrayBuffer(1);
									let dataView = new DataView(buffer);
									dataView.setUint8(0, 0x04);
									that.send(buffer);
								}
								// console.log(str, strHex.toString())
							}
			
							// console.log('characteristic value comed:', characteristic);
							// console.log('ab2hex=========', that.ab2hex(characteristic.value));
							// console.log('arrayBufferUTF8ToStr=========', that.arrayBufferUTF8ToStr(
							// 	characteristic.value));
							// console.log('hex2int=========', that.hex2int(characteristic.value));
			
						});
					},
					fail(res) {
						console.error(res);
					}
				})
			},
			
			//发送数据
			send(buffer) {
				let that = this;
				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId,
					value: buffer,
					success(res) {
			
					},
					fail(res) {
						if (res.errCode === 10006) {
							clearInterval(that.timerInterVal);
						}
					}
				})
			},
			// 十进制转十六进制
			jinzhi_change(num, system) {
				// 十进制转其它进制，仅支持到十六进制
				var shiliu = [
						'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G'
					],
					sl_arr = [];
				do {
					var fl_sl = Math.floor(num / system);
					var yu_sl = num % system;
			
					sl_arr.unshift(shiliu[yu_sl]); //往数组开头添加一条数据
					num = fl_sl;
				} while (num > 0)
				return sl_arr.join(''); //拼接数组成字符串
			},
			//字符串转16进制码
			str_to_hex(str) {
				var val = "";
				for (var i = 0; i < str.length; i++) {
					if (val == "")
						val = str.charCodeAt(i).toString(16);
					else
						val += "," + str.charCodeAt(i).toString(16);
				}
				return val.split(",");
			},
			// ArrayBuffer转16进度字符串示例 
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			
			hex2int(hex) { //16进制转10进制
				var len = hex.length,
					a = new Array(len),
					code;
				console.log(len);
				for (var i = 0; i < len; i++) {
			
					code = hex.charCodeAt(i);
					if (48 <= code && code < 58) {
						code -= 48;
					} else {
						code = (code & 0xdf) - 65 + 10;
					}
					a[i] = code;
				}
			
				return a.reduce(function(acc, c) {
					acc = 16 * acc + c;
					return acc;
				}, 0);
			
			},
			searchCarState(e) {
				var buffer = new ArrayBuffer(15);
				let dataView = new DataView(buffer);
				for (let i = 0; i < 15; i++) {
					if(i == 0)
					{
						if(e == true)
						{
							dataView.setUint8(i, 0x01);
						}
						else
						{
							if(this.isbtn == true)
							{
								this.isbtn = false;
								dataView.setUint8(i, 0x03);
							}
							else
							{
								dataView.setUint8(i, 0x00);
							}
							
						}
					}
					else if(i == 1)
					{
						dataView.setUint8(i,this.oneName);
					}
					else if(i == 3 || i == 4)
					{
						if(i == 3)
						{
							let index = this.twoName / 256;
							dataView.setUint8(i,index);
						}
						else
						{
							let index = this.twoName % 256;
							dataView.setUint8(i,index);
						}
						
					}

					else if(i == 5 || i == 6)
					{
						if(i == 5)
						{
							let index = this.threeName / 256;
						dataView.setUint8(i,index);
							
						}
						else
						{
							let index = this.threeName % 256;
							dataView.setUint8(i,index);
						}
					}
					else if(i == 7 || i == 8)
					{
						if(i == 7)
						{
							let index = this.fourName * 10 / 256;
							dataView.setUint8(i,index);
							
						}
						else
						{
							let index = this.fourName *10 % 256;
						dataView.setUint8(i,index);
						}
					}
					else if(i == 9 || i == 10)
					{
						if(i == 9)
						{
							let index = this.fiveName / 256;
							dataView.setUint8(i,index);
							
						}
						else
						{
							let index = this.fiveName % 256;
							dataView.setUint8(i,index);
						}
					}
					else if(i == 11 || i == 12)
					{
						if(i == 11)
						{
							let index = this.sixName / 256;
							dataView.setUint8(i,index);
							
						}
						else
						{
							let index = this.sixName % 256;
							dataView.setUint8(i,index);
						}
					}
					else if(i == 13 || i == 14)
					{
						if(i == 13)
						{
							let index = this.severName *10 / 256;
							dataView.setUint8(i,index);
						}
						else
						{
							let index = this.severName *10 % 256;
							dataView.setUint8(i,index);
						}
					}

				}
				this.crcBuffer = this.crc16modbus(buffer);
				var newbuffer = new ArrayBuffer(19)
				let newDataView = new DataView(newbuffer);
				newDataView.setUint8(0, 0xA5);
				for (var i = 0; i < 15; i++) {
					newDataView.setUint8(i + 1, dataView.getUint8(i));
			
				}
				newDataView.setUint8(16, this.crcBuffer[1]);
				newDataView.setUint8(17, this.crcBuffer[0]);
				newDataView.setUint8(18, 0x5A);
				return newbuffer;
			},
			arrayBufferUTF8ToStr(array) {
				let that = this;
				var out, i, len, c;
				var char2, char3;
				if (array instanceof ArrayBuffer) {
					array = new Uint8Array(array);
				}
				console.log("进来了", array.length);
				out = "";
				len = array.length;
				// //放电正常
				// isSuccse:false,
				// //放电异常
				// isError:false,
				// car:'',
				// thoroughfareOne:'',
				// thoroughfareTwo:'',
				if(this.isFirst == false)
				{
					this.isFirst = true;
					this.oneName = array[29];
				}
				this.statuslist[0].value = ((array[30] * 256 + array[31]) / 10).toFixed(1);
				this.statuslist[6].value = (array[32] * 256 + array[33])
				this.statuslist[9].value = (array[34] * 256 + array[35]) 
				this.statuslist[3].value = array[36];
				this.statuslist[4].value = (array[37] / 10).toFixed(1);
				//((array[38] * 256 + array[39]) / 1000).toFixed(1);
				this.statuslist[5].value = (((array[38] * 256 + array[39])-4000) / 10).toFixed(1);
				this.statuslist[7].value = (array[40] * 256 + array[41])
				this.statuslist[8].value = ((array[42] * 256 + array[43]) / 10).toFixed(1);
				this.statuslist[10].value = (array[44] * 256 + array[45])
				this.statuslist[11].value = ((array[46] * 256 + array[47]) / 10).toFixed(1);
				this.statuslist[12].value = (array[48] * 256 + array[49])
				this.statuslist[13].value = (array[50] * 256 + array[51])
				this.statuslist[14].value = (array[52] * 256 + array[53])
				this.statuslist[15].value = (array[54] * 256 + array[55])
				this.statuslist[16].value = (array[56] * 256 + array[57])
				this.statuslist[17].value = (array[58] * 256 + array[59])
				this.statuslist[1].value = array[60];
				this.statuslist[2].value = array[61];
				this.statuslist[18].value = String.fromCharCode(array[62])+String.fromCharCode(array[63])+String.fromCharCode(array[64])
				let strHex ="";
				let str = "";
				for (let i =1; i < 27; i++) {
					strHex = strHex + array[i].toString(16).padStart(2, "0")
					str = str + String.fromCharCode(array[i])
				};
				this.statuslist[19].value = str;
				// if (array[27] == 0) {
				// 	this.isSuccse = false;
				// 	this.isError = false;
				// } else if (array[27] == 2) {
				// 	this.isSuccse = true;
				// 	this.isError = false;
				// 	this.car = array[28];
				// 	this.thoroughfareOne = ((array[32] * 256 + array[33]) / 1000).toFixed(1);
				// 	this.thoroughfareTwo = ((array[34] * 256 + array[35]) / 1000).toFixed(1);
				// } else if (array[27] == 3) {
				// 	this.isSuccse = false;
				// 	this.isError = true;
				// 	this.errorName = array[36];
				// }
				if (this.isEnd === true) {
					this.isEnd = false;
					let buffer = that.searchCarState(false);
					this.timerInterVal = setInterval(() => {
						that.send(buffer);
					}, 500);
				}
				i = 0;
				while (i < 27) {
					c = array[i++];
					console.log("c",array[i++],i);
					switch (c >> 4) {
						case 0:
						case 1:
						case 2:
						case 3:
						case 4:
						case 5:
						case 6:
						case 7:
							// 0xxxxxxx
							out += String.fromCharCode(c);
							break;
						case 12:
						case 13:
							// 110x xxxx   10xx xxxx
							char2 = array[i++];
							out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
							break;
						case 14:
							// 1110 xxxx  10xx xxxx  10xx xxxx
							char2 = array[i++];
							char3 = array[i++];
							out += String.fromCharCode(((c & 0x0F) << 12) |
								((char2 & 0x3F) << 6) |
								((char3 & 0x3F) << 0));
							break;
					}
				}
				// console.log("out",out);
			
				// return out;
			},
			crc16modbus(str) {
				let crc = 0x0000; // 效验初始值
				const buffer = Buffer.from(str)
				for (const byte of buffer) {
					for (let j = 0; j < 8; j++) {
						const bit = ((byte >> (7 - j) & 1) == 1);
						const c15 = ((crc >> 15 & 1) == 1);
						crc <<= 1;
						if (c15 ^ bit)
							crc ^= 0x1021;
					}
				}
				crc &= 0xffff;
				var crcLow = crc & 0xFF;
				var crcHigh = (crc >> 8) & 0xFF;
				return [crcLow, crcHigh];
			},
			writeTest(buffer, type, title) {
				let that = this;
				let tmpBuffer;
				if (type == 1) {
					if (title == 'name') {
						tmpBuffer = new ArrayBuffer(3);
						let dataView = new DataView(tmpBuffer);
						dataView.setUint8(0, 0x01);
						dataView.setUint8(1, 0x00);
						dataView.setUint8(2, 0xFF);
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								console.log("发送成功")
								that.writeTest(that.bufferName, 0, "");
							},
							fail: () => {
								console.log("发送失败");
							}
						})
					}
					if (title == "file") {
						tmpBuffer = new ArrayBuffer(3);
						let dataView = new DataView(tmpBuffer);
						dataView.setUint8(0, 0x02);
						if (this.index < 10) {
							dataView.setUint8(1, "0x0" + this.index);
							dataView.setUint8(2, ~("0x0" + this.index));
						} else {
							dataView.setUint8(1, this.index);
							dataView.setUint8(2, ~this.index);
						}
			
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								console.log("发送成功")
								that.writeTest(that.bufferName, 0, "");
							},
							fail: () => {
								console.log("发送失败");
							}
						})
					}
				} else {
					if (this.bytes > 20) {
						tmpBuffer = buffer.slice(this.pos, this.pos + 20);
						this.pos += 20;
						this.bytes -= 20;
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								console.log("发送成功")
								that.writeTest(that.bufferName, 0, "");
							},
							fail: () => {
								console.log("发送失败");
							}
						})
					} else {
						tmpBuffer = buffer.slice(this.pos, this.pos + this.bytes);
						this.pos += this.bytes;
						this.bytes -= this.bytes;
						uni.writeBLECharacteristicValue({
							deviceId: that.deviceId,
							serviceId: that.serviceId,
							characteristicId: that.characteristicId,
							value: tmpBuffer,
							success: () => {
								console.log("发送成功")
							},
							fail: () => {
								console.log("发送失败");
							}
						})
					}
				}
			
			},
			updateHardware() {
				let arrayBufferFileName = this.str_to_hex("ver:change");
			
				console.log("hex", arrayBufferFileName);
				var buffer = new ArrayBuffer(arrayBufferFileName.length);
				let dataView = new DataView(buffer);
				for (let i = 0; i < arrayBufferFileName.length; i++) {
					console.log("0x" + arrayBufferFileName[i]);
					dataView.setUint8(i, "0x" + arrayBufferFileName[i]);
				}
			
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					value: buffer,
					success(res) {
			
					},
					fail(res) {
						console.error('error,write', res.errCode);
					}
				})
			},
			// closeCar() {
			// 	let that = this;
			// 	clearInterval(that.timerInterVal);
			// 	var buffer = new ArrayBuffer(15);
			// 	let dataView = new DataView(buffer);
			// 	for (let i = 0; i < 15; i++) {
			// 		if (i == 0) {
			// 			dataView.setUint8(i, 0x01);
			// 		} else if (i == 2) {
			// 			dataView.setUint8(i, 0x01);
			// 		} else {
			// 			dataView.setUint8(i, 0x00);
			// 		}
			// 	}
			// 	that.crcBuffer = that.crc16modbus(buffer);
			// 	var newbuffer = new ArrayBuffer(19)
			// 	let newDataView = new DataView(newbuffer);
			// 	newDataView.setUint8(0, 0xA5);
			// 	for (var i = 0; i < 15; i++) {
			// 		newDataView.setUint8(i + 1, dataView.getUint8(i));
			
			// 	}
			// 	newDataView.setUint8(16, that.crcBuffer[1]);
			// 	newDataView.setUint8(17, that.crcBuffer[0]);
			// 	newDataView.setUint8(18, 0x5A);
			// 	that.isEnd = true;
			// 	that.send(newbuffer);
			// }
		}
	}
</script>

<style lang="scss" scoped>
.hardware{
	width: 100%;
	height: 100%;
	padding:0 20rpx;
	box-sizing: border-box;
	.row_content{
	   width: 100%;
	   padding:20rpx 0;
	   display: flex;
	   flex-direction: row;
	   align-items: center;
	   border-bottom:2rpx solid #666;
	   .row_one{
		   flex:1;
		   text-align: center;
		   font-size: 30rpx;
	   }
	   .row_two{
		   flex:2;
		   padding:10rpx 0;
		   box-sizing: border-box;
		   border:2rpx solid #666;
		   
	   }
	}
			.contentBox {
				width: 100%;
				margin-top: 10rpx;
				display: flex;
				flex-direction: row;
				flex-wrap: wrap;
				justify-content: space-between;
	
				.itemBox {
					width: 30%;
					display: flex;
					flex-direction: column;
					align-items: center;
					margin-bottom: 30rpx;
	
					.itemOneText {
						font-size: 14px;
						color: #999;
					}
	
					.itemTwoText {
						margin-top: 10rpx;
						font-size: 13px;
						font-weight: bold;
						text-align: center;
					}
				}
			}
}
</style>
